import snakeCase from 'lodash/snakeCase';

import fetch from 'fermionjs/lib/fetch';
import urlPathConcat from '@kuiper-helpers/url-path-concat/dist';
import pkg from '../../../package.json';

import errorCodesBuilder from '../helpers/errorCodesBuilder';

const errorCodes = errorCodesBuilder();

function request(sever, { url: urlPath, body, cookie }) {
	const {
		log,
		app: {
			config: {
				[pkg.name]: { serviceApi, token },
			},
		},
	} = sever;

	const url = urlPathConcat(serviceApi, urlPath);
	log.info({ url }, '请求任务调度');

	return fetch(url, {
		body: JSON.stringify(body),
		method: 'POST',
		headers: {
			cookie: cookie || `token=${token}`,
			'content-type': 'application/json',
		},
	})
		.then(response => {
			if (response.code !== 200) {
				throw new Error(JSON.stringify(response));
			}
			log.debug({ url, body, response }, '请求任务调度成功');
			return response;
		})
		.catch(err => {
			const error = errorCodes['[01]请求任务调度失败']
				.from(err)
				.msg(err.response?.msg)
				.addition(err.response);
			log.error({ error, url, body }, error.rawMessage);
			throw error;
		});
}

export function createOrUpdateTask({
	taskType,
	body,
	triggerType = 'schedule',
}) {
	const url = urlPathConcat('/api/v2/jobs', snakeCase(taskType), triggerType);
	// 目前预登录不支持http,ping,ssl
	if ('http,ping,ssl'.includes(snakeCase(taskType))) {
		delete body.prelogin;
	}
	return request(this, { url, body });
}

export function retryTask({ jobId, taskId }) {
	return request(this, {
		url: '/api/v2/jobs/rescan',
		body: { jobId, taskId },
	});
}

export function removeTask(body) {
	return request(this, {
		url: '/api/v2/jobs/tasks/remove',
		body, // { jobId, taskIds }
	});
}

export function removeTaskSession({ jobId, taskSessionIds }) {
	const ids = taskSessionIds.filter(Boolean);
	if (ids.length === 0) return Promise.resolve();
	return request(this, {
		url: '/api/v2/jobs/task_sessions/remove',
		body: { jobId, taskSessionIds: ids },
	});
}

export function stopTask({ jobId, taskIds }) {
	return request(this, {
		url: '/api/v2/jobs/tasks/stop',
		body: { jobId, taskIds },
	});
}

export function stopTaskSession({ jobId, taskSessionIds }) {
	return request(this, {
		url: '/api/v2/jobs/task_sessions/stop',
		body: { jobId, taskSessionIds },
	});
}
